import React, { Component } from 'react';
import { Card, Spin, Select } from 'antd';
import PropTypes from 'prop-types';
import ReactEcharts from 'echarts-for-react';
import NoData from '../NoData/NoData';
import { generateSunburstChartOption } from '@/utils/echarts-figures.js';

const Option = Select.Option;
const filterData = (arr, time) => {
  if (arr.length === 0) {
    return null;
  }
  const chart = arr.filter(v => v.type === time);
  return {
    numbers: chart.length > 0 ? chart[0].data.numbers : [],
    layer: chart.length > 0 ? chart[0].data.layer : 1,
  };
};
/**
 * 静态相似图表
 */
export default class Test extends Component {
  static propTypes = {
    isLoading: PropTypes.bool,
    staticChart: PropTypes.array.isRequired, // 静态相似数据
    desc: PropTypes.string, // 静态相似指标解释
  };

  static defaultProps = {
    desc: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      curTime: '当前期',
      hasData: true,
      option: generateSunburstChartOption('', props.staticChart.numbers, props.staticChart.layer),
    };
  }

  /**
   * 从属性有数据中筛选出对应type的数据
   */
  static getDerivedStateFromProps(nextProps, prevState) {
    const { staticChart } = nextProps;
    const { curTime } = prevState;
    // staticChart是静态相似数组
    if (staticChart && staticChart.length > 0) {
      const selectData = filterData(staticChart, curTime);
      if (selectData) {
        return {
          hasData: true,
          option: generateSunburstChartOption('静态相似公司', selectData.numbers, selectData.layer),
        };
      }
    }
    return {
      hasData: false,
    };
  }

  onChange(curTime) {
    this.setState({
      curTime,
    });
  }

  render() {
    const times = ['当前期', '一年', '两年', '三年'];
    const { isLoading, staticChart, desc } = this.props;
    const { hasData } = this.state;
    return (
      <div className="chart-container">
        <Card>
          <Spin spinning={!!isLoading} style={{ width: '100%' }}>
            <Select
              style={{ position: 'absolute', left: '10px', top: '0px', zIndex: '2' }}
              defaultValue={this.state.curTime}
              onChange={this.onChange.bind(this)}
            >
              {times.map(time => (
                <Option key={time} value={time}>
                  {time}
                </Option>
              ))}
            </Select>

            {!hasData && <NoData />}

            {hasData && (
              <ReactEcharts option={this.state.option} style={{ width: '100%', height: '680px' }} />
            )}

            <div>
              <div style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '10px' }}>
                指标解释
              </div>
              <div className="tab-text">{desc}</div>
            </div>
          </Spin>
        </Card>
      </div>
    );
  }
}
